<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <div class="text item">
        <el-form
          :model="newQuestionForm"
          :rules="newQuestionRules"
          ref="questionRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              v-model="newQuestionForm.subjectID"
              placeholder="请选择"
              style="width: 400px;"
              @change="subjectChange"
            >
              <el-option
                v-for="(item, index) in subjectsList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop="catalogID">
            <el-select
              v-model="newQuestionForm.catalogID"
              placeholder="请选择"
              style="width: 400px;"
            >
              <el-option
                v-for="(item, index) in directorysList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select
              v-model="newQuestionForm.enterpriseID"
              placeholder="请选择"
              style="width: 400px;"
            >
              <el-option
                v-for="(item, index) in companysList"
                :key="index"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市:" prop="province">
            <el-select
              v-model="newQuestionForm.province"
              placeholder="请选择"
              style="width: 198px; margin-right: 2px;"
            >
              <el-option
                v-for="(item, index) in provincesList()"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select
              v-model="newQuestionForm.city"
              placeholder="请选择"
              style="width: 198px;"
              prop="city"
            >
              <el-option
                v-for="(item, index) in cityList(newQuestionForm.province)"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向:" prop="direction">
            <el-select
              v-model="newQuestionForm.direction"
              placeholder="请选择"
              style="width: 400px;"
            >
              <el-option
                v-for="(item, index) in direction"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group v-model="newQuestionForm.questionType">
              <el-radio
                :label="'1'"
              >单选</el-radio>
              <el-radio
                :label="'2'"
              >多选</el-radio>
              <el-radio
                :label="'3'"
              >简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="newQuestionForm.difficulty">
              <el-radio
                :label="'1'"
              >简单</el-radio>
              <el-radio
                :label="'2'"
              >一般</el-radio>
              <el-radio
                :label="'3'"
              >困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干:" prop="question">
            <quill-editor 
              v-model="newQuestionForm.question"
              :options="editorOption"
              ref="myQuillEditor"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item label="选项:" v-if="newQuestionForm.questionType !== '3'">
          <el-radio-group
            v-if="newQuestionForm.questionType === '1'"
            v-model="radioItem"
          >
            <el-col 
              class="el-row-option"
              v-for="(item, index) in newQuestionForm.options"
              :key="index"
            >
              <el-radio 
                :label="item.code"
                :value="item.isRight"
              />
              <el-input
                v-model="item.title"
                style="width: 240px;"
              />
              <el-upload
                :action="item.img"
              >
                <el-avatar
                  shape="square"
                  fit="cover"
                >
                  <span slot="default">上传图片</span>
                  <i class="el-icon-circle-close"></i>
                </el-avatar>
              </el-upload>
            </el-col>
          </el-radio-group>
          <el-checkbox-group
            v-if="newQuestionForm.questionType === '2'"
            v-model="checkItem"
          >
            <el-row 
              class="el-row-option"
              v-for="(item, index) in newQuestionForm.options"
              :key="index"
            >
            <el-checkbox 
              :label="item.code"
              :value="item.isRight"
            />
            <el-input
              v-model="item.title"
              style="width: 240px;"
            />
            <el-upload
              :action="item.img"
            >
              <el-avatar
                shape="square"
                fit="cover"
              >
                <span slot="default">上传图片</span>
                <i class="el-icon-circle-close"></i>
              </el-avatar>
            </el-upload>
            </el-row>
          </el-checkbox-group><br>
          <el-button
            type="danger"
            :disabled="newQuestionForm.questionType !== '2' ? true : false"
            @click="addOptionItem"
          >+增加选项与答案</el-button>
          </el-form-item>
          <el-form-item label="解析视频:">
            <el-input
              style="width: 50%;"
              v-model="newQuestionForm.videoURL"
            />
          </el-form-item>
          <el-form-item label="答案解析:" prop="answer">
            <quill-editor 
              v-model="newQuestionForm.answer"
              :options="editorOption"
              ref="myQuillEditor"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item label="题目备注:">
            <el-input
            v-model="newQuestionForm.remarks"
              type="textarea"
              style="width: 400px;"
            />
          </el-form-item>
          <el-form-item label="试题标签:">
            <el-select
              v-model="newQuestionForm.tags"
              placeholder="请选择试题标签"
              clearable
              style="width: 400px;"
              multiple
              :multiple-limit="5"
              collapse-tags
            >
              <el-option
                v-for="(item, index) in tagsList"
                :key="index"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="success"
              @click="submitUpdateForm(newQuestionForm)"
              v-if="otherId"
            >确认修改</el-button>
            <el-button
              type="primary"
              @click="submitAddForm(newQuestionForm)"
              v-else
            >确认提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { simple as subjectsSimple } from '@/api/hmmm/subjects'
import { simple as directorysSimple } from '@/api/hmmm/directorys'
import { simple as tagsSimple } from '@/api/hmmm/tags'
import { list as companysList } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
import { add as questionAdd, detail as questionDetail, update as questionUpdate } from '@/api/hmmm/questions'

export default {
  name: 'QuestionsNew',
  components: {
    quillEditor
  },
  props: {},
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      // ASCII表A数字
      uploadPictureLock: false,
      num: 68,
      newQuestionForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
        {
          code: 'A', // 代码
          // code: 'A',
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 是否为正确答案
        },
        {
          code: 'B', // 代码
          // code: 'A',
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 是否为正确答案
        },
        {
          code: 'C', // 代码
          // code: 'A',
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 是否为正确答案
        },
        {
          code: 'D', // 代码
          // code: 'A',
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 是否为正确答案
        }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      newQuestionRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'change' }
        ],
      },
      // 富文本框配置
      editorOption: {
        placeholder: "请在这里输入",
        modules:{
          toolbar:[
            ['bold', 'italic', 'underline', 'strike'],    //加粗，斜体，下划线，删除线
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],     //列表
            ['blockquote', 'code-block'],     //引用，代码块
            ['image','link']    //上传图片、上传视频
          ]
        }
      },
      questionOption: {
        code: '', // 代码
        // code: 'A',
        title: '', // 标题
        img: '', // 图片URL
        isRight: false // 是否为正确答案
      },
      // 题目的选中项code
      radioItem: '',
      checkItem: [],
      // 学科列表
      subjectsList: [],
      // 目录列表
      directorysList: [],
      // 企业列表
      companysList: [],
      // 标签列表
      tagsList: [],
      // 城市列表
      provincesList: provinces,
      cityList: citys,
      questionType, // 题型
      difficulty, // 难度
      direction, // 方向
      // 其他页面传过来的id
      otherId: this.$route.query.id
    }
  },
  created () {
    this.getQuestionsList()  
    this.getCompanysList()
    // console.log(this.otherId)
    // console.log(String.fromCharCode(65))
    // this.questionOptions()
    // this.newQuestionForm.options[0].code = String.fromCharCode(this.num)
    if (this.$route.query.id) {
      this.getDirectorysList(this.newQuestionForm.subjectID)
      this.getTagsList()
      this.getquestionForm(this.$route.query.id)
    }
  },
  mounted() {},
  methods: {
    // 获取学科列表
    async getQuestionsList() {
      const { data } = await subjectsSimple()
      this.subjectsList = data
    },
    // 获取目录列表
    async getDirectorysList(id) {
      const { data } = await directorysSimple(id)
      // console.log(data)
      this.directorysList = data
    },
    // 获取企业列表
    async getCompanysList() {
      const { data } = await companysList()
      // console.log(data)
      this.companysList = data.items
    },
    // 获取标签列表
    async getTagsList() {
      const { data } = await tagsSimple()
      // console.log(data)
      this.tagsList = data
    },
    subjectChange () {
      this.getDirectorysList()
      this.getTagsList()
    },
    // 提交
    submitAddForm () {
      this.$refs.questionRuleForm.validate(async (valid) => {
          if (valid) {
            this.newQuestionForm.tags  = this.newQuestionForm.tags.join(',')
            await questionAdd(this.newQuestionForm)
            this.$message.success('提交成功')
            this.$refs.questionRuleForm.resetFields()
            this.$router.push('list')
          } else {
            return false;
          }
        })
      
    },
    // 修改submitUpdateForm
    submitUpdateForm () {
      this.$refs.questionRuleForm.validate(async (valid) => {
          if (valid) {
            this.newQuestionForm.tags  = this.newQuestionForm.tags.join(',')
            await questionUpdate(this.newQuestionForm)
            this.$message.success('提交成功')
            this.$refs.questionRuleForm.resetFields()
            this.$router.push('list')
            // console.log(data)
          } else {
            return false;
          }
        })
      
    },
    // 获取数据
    async getquestionForm (id) {
      const { data } = await questionDetail({ id: id })
      data.tags = data.tags.split(',')
      if (data.difficulty === '简单') {
        data.difficulty = '1'
      } else if (data.difficulty === '一般') {
        data.difficulty = '2'
      } else if (data.difficulty === '困难') {
        data.difficulty = '3'
      }
      if (data.questionType === '单选') {
        data.questionType = '1'
      } else if (data.questionType === '多选') {
        data.questionType = '2'
      } else if (data.questionType === '简答') {
        data.questionType = '3'
      }
      data.options.forEach(item => {
        if (data.questionType === '1'){
          if (item.isRight === 1) {
            this.radioItem = item.code
          }
        } else if (data.questionType === '2') {
          // console.log(1111)
          if (item.isRight === 1) {
            // console.log(111)
            this.checkItem.push(item.code)
            // console.log(this.checkItem)
          }
        }
      })
      this.newQuestionForm = data
    },
    // 添加选项
    addOptionItem () {
      this.num++
      this.questionOption.code = String.fromCharCode(this.num)
      const questionOption = {...this.questionOption}
      this.newQuestionForm.options.push(questionOption)
    },
    handleRemove(file, fileList) {
        console.log(file, fileList);
      },
    handlePictureCardPreview(response, file, fileList) {
      console.log(response, file, fileList)
    },
    uploadPicture () {
      console.log(2222)
    }
  },
  computed: {
    
  },
  watch: {
    radioItem: function () {
      // this.newQuestionForm.questionType = this.questionType
      if (this.newQuestionForm.questionType === '1') {
        this.newQuestionForm.options.forEach(item => {
        if (this.radioItem === item.code) {
          return item.isRight = true
        } else {
          return item.isRight = false
        }
      })
      }
    },
    checkItem: function () {
      if (this.newQuestionForm.questionType === '2') {
        this.newQuestionForm.options.forEach(itemO => {
          // console.log(itemO)
          return this.checkItem.forEach(item => {
            console.log(111)
            if (item === itemO.code) {
              // console.log(111)
              return itemO.isRight = true
            } else {
              return itemO.isRight = false
            }
          })
        })
      }
    },
    // questionType: function () {
    //   // console.log(1111111)
    //   if (this.questionType === '2' && this.optionItem.length === 0) {
        
    //   } else if (this.questionType === '1' && this.optionItem.length === 0) {
    //     this.radioItem = [...this.checkItem]
    //   }
    // }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.el-row-option{
  display: flex;
  flex-direction: row;
  // justify-content: center;
  align-items: center;
  .question-options-item{
    margin: 0 15px;
  }
  .el-radio,
  .el-checkbox{
    margin-right: 15px;
  }
  .picture-col{
    margin: 0;
  }
  .el-upload--text {
    width: 100px;
    height: 60px;
    margin: 10px 6px;
    }
    .el-avatar--square {
      position: relative;
      width: 100px;
      height: 60px;
      background-color: #fff;
      color: #000;
      cursor: pointer;
      line-height: 60px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      overflow: unset;
      .el-icon-circle-close {
        position: absolute;
        top: 0;
        right: 0;
        transform: translate(50%, -50%);
      }
    }
  
}
.el-upload--picture-card{
  width: 100px;
  height: 60px;
}
.el-textarea__inner {
    min-height: 96px;
  }
  .el-select--medium {
    margin-right: 2px !important;
  }
.dialog_img{
    width: 100%;
  }
  .btnAdd{
    margin-top: 20px;
  }
</style>
